<template>
  <div>
    <el-dialog title="自动设置" :visible.sync="autoVisible" width="596px">
      <el-form
        ref="autoform"
        :model="autoform"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-row class="wrap">
          <span class="title-header">自动提醒</span>
        </el-row>
        <div class="textLine">
          <el-checkbox
            v-model="autoform.checked1"
            style="margin-right: 10px"
          ></el-checkbox
          >超过
          <el-input
            v-model="autoform.managerOverdueDay"
            style="width: 56px; margin: 0 6px"
          >
          </el-input
          >天，客户未分配跟进人员，次日8:00提醒管理员分配，选择接收提醒管理员
<!--          <el-time-picker-->
<!--            v-model="autoform.managerNextTime"-->
<!--            style="width: 106px; margin: 0 6px"-->
<!--            suffix-icon="el-icon-time"-->
<!--            clearable-->
<!--            value-format="HH:mm"-->
<!--            format="HH:mm"-->
<!--            :editable="false"-->
<!--          >-->
<!--          </el-time-picker>-->
<!--          <el-cascader-->
<!--            :options="distributeEmployeList"-->
<!--            @active-item-change="distributeEmployeListChange"-->
<!--            :props="receiveProps"-->
<!--            :show-all-levels="false"-->
<!--            v-model="autoform.receiveManager"-->
<!--            style="margin: 0 6px"-->
<!--          ></el-cascader>-->
          <div v-if="scrmPersonSopUserRels.length > 0" style="display: inline-block ; margin-right: 8px">
            <el-tag v-for="item in scrmPersonSopUserRels" :key="item.userId" closable
                    @close="handleClose(item)">
              {{ item.userName || item.name || '' }}
            </el-tag>
          </div>
          <el-button class="button-new-tag" size="small" @click="handleClick">
            <svg-icon icon-class="add" /> 添加员工
          </el-button>
        </div>
        <div class="textLine">
          <el-checkbox
            v-model="autoform.checked2"
            style="margin-right: 10px"
          ></el-checkbox
          >超过
          <el-input
            v-model="autoform.employeOverdueDay"
            style="width: 56px; margin: 0 6px"
          >
          </el-input
          >天，员工未添加用户，次日8:00自动提醒成员添加
<!--          <el-time-picker-->
<!--            v-model="autoform.employeNextTime"-->
<!--            style="width: 106px; margin: 0 6px"-->
<!--            suffix-icon="el-icon-time"-->
<!--            clearable-->
<!--            value-format="HH:mm"-->
<!--            format="HH:mm"-->
<!--            :editable="false"-->
<!--          >-->
<!--          </el-time-picker>-->
        </div>
        <el-row class="wrap">
          <span class="title-header">自动分配</span>
        </el-row>
        <div class="textLine">
          <el-checkbox
            v-model="autoform.checked3"
            style="margin-right: 10px"
          ></el-checkbox
          >超过
          <el-input
            v-model="autoform.autoDay"
            style="width: 56px; margin: 0 6px"
          >
          </el-input
          >天，员工未添加客户， 自动分配给兜底员工
          <div v-if="scrmPersonSopUserRels1.length > 0" style="display: inline-block ; margin-right: 8px">
            <el-tag v-for="item in scrmPersonSopUserRels1" :key="item.userId" closable
                    @close="handleClose1(item)">
              {{ item.userName }}
            </el-tag>
          </div>
          <el-button class="button-new-tag" size="small" @click="handleClick1">
            <svg-icon icon-class="add" /> 添加员工
          </el-button>

        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="autoVisible = false">取消</el-button>
        <el-button type="primary" @click="handelConfirm" v-preventReClick="1000"
          >确定</el-button
        >
      </div>
    </el-dialog>

<!--    &lt;!&ndash;  接受提醒管理员&ndash;&gt;-->
<!--    <SelectCus :selectList="tableDataName" :visible.sync="selectUserVisible" :userList="[]"-->
<!--               @confirm="selectUserConfirm" :is-active="'1'"></SelectCus>-->

<!--&lt;!&ndash;    兜底员工&ndash;&gt;-->
<!--    <SelectCus :selectList="tableDataName1" :visible.sync="selectUserVisible1" :userList="[]"-->
<!--               @confirm="selectUserConfirm1" :is-active="'1'"></SelectCus>-->

    <!--  接受提醒管理员-->
    <SelectUser :selectList="tableDataName" :visible.sync="selectUserVisible" :userList="[]"
               @confirm="selectUserConfirm" :is-active="'1'"></SelectUser>

    <!--    兜底员工-->
    <SelectUser :selectList="tableDataName1" :visible.sync="selectUserVisible1" :userList="[]"
               @confirm="selectUserConfirm1" :is-active="'1'"></SelectUser>
  </div>
</template>
<script>
import {
  addWainingAuto,
  getCustomers,
  queryCustomers,
  queryWarningAuto,
} from "@/api/beathAdd";
// import Treeselect from "@riophae/vue-treeselect";
// import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// import { string } from "clipboard";
import SelectCus from '@/views/customerOperations/attractCustomers/component/selectCus.vue'
import SelectUser from "@/components/SelectUser/index.vue";
export default {
  name: "AutoWarn",
  components: {
    // Treeselect
    SelectCus,
    SelectUser
  },
  props: {
    // 添加标签显隐
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      receiveProps: { multiple: true },
      autoform: {
        checked1: undefined,
        managerOverdueDay: undefined,
        // managerNextTime: undefined,
        receiveManager: [],
        checked2: undefined,
        employeOverdueDay: undefined,
        // employeNextTime: undefined,
        checked3: undefined,
        autoDay: undefined,
        employeBottom: [],
      },
      rules: {},
      //员工数据下拉框
      distributeEmployeList: [],
      deptList: [],

      scrmPersonSopUserRels:[],
      tableDataName:[],
      selectUserVisible : false,

      scrmPersonSopUserRels1:[],
      tableDataName1:[],
      selectUserVisible1 : false,
    };
  },
  computed: {
    autoVisible: {
      get() {
        if (this.visible) {
          this.$nextTick(() => {
            // this.$refs["autoform"].clearValidate();
          });
        }
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  watch: {},
  created() {
    this.queryWarningAuto();
  },
  mounted() {},
  methods: {
    onOpen() {},
    onClose() {
      this.$refs["autoform"].resetFields();
    },
    close() {
      this.$emit("update:visible", false);
    },
    handelConfirm() {
      let flag = true;
      let Regx = /^[1-9]{1,}[\d]*$/;
      if (this.autoform.checked1) {
        if (!this.autoform.managerOverdueDay) {
          this.msgError("超过天数不能为空！");
          flag = false;
          return;
        } else if (!Regx.test(this.autoform.managerOverdueDay)) {
          this.msgError("超过天数格式错误！");
          flag = false;
          return;
        }
        // else if (!this.autoform.managerNextTime) {
        //   this.msgError("次日时间不能为空！");
        //   flag = false;
        //   return;
        // }
        else
        // if (!this.autoform.receiveManager) {
          if (+this.scrmPersonSopUserRels.length === 0) {
          this.msgError("接收提醒管理员不能为空！");
          flag = false;
          return;
        }
      }
      if (this.autoform.checked2) {
        if (!this.autoform.employeOverdueDay) {
          this.msgError("超过天数不能为空！");
          flag = false;
          return;
        } else if (!Regx.test(this.autoform.employeOverdueDay)) {
          this.msgError("超过天数格式错误！");
          flag = false;
          return;
        }
        // else if (!this.autoform.employeNextTime) {
        //   this.msgError("次日时间不能为空！");
        //   flag = false;
        //   return;
        // }
      }
      if (this.autoform.checked3) {
        console.log(this.scrmPersonSopUserRels1 , 'scrmPersonSopUserRels1' , '接收提醒管理员')
        if (!this.autoform.autoDay) {
          this.msgError("超过天数不能为空！");
          flag = false;
          return;
        } else if (!Regx.test(this.autoform.autoDay)) {
          this.msgError("超过天数格式错误！");
          flag = false;
          return;
        } else
        // if (!this.autoform.employeBottom) {
          if (+this.scrmPersonSopUserRels1.length === 0) {
          this.msgError("接收提醒管理员不能为空！");
          flag = false;
          return;
        }
      } else {
        flag = true;
      }
      this.$refs["autoform"].validate((valid) => {
        if (valid && flag) {
          let param = [];
          if (this.autoform.checked1) {
            let obj1 = {};
            obj1.managerOverdueDay = this.autoform.managerOverdueDay;
            // obj1.managerNextTime = this.autoform.managerNextTime || '';
            // obj1.managerNextTime = '';
            obj1.receiver = [];
            this.scrmPersonSopUserRels.forEach((item) => {
              obj1.receiver.push(item.userId);
            });
            obj1.warningType = "0";
            param.push(obj1);
          }
          if (this.autoform.checked2) {
            let obj2 = {};
            obj2.managerOverdueDay = this.autoform.employeOverdueDay;
            // obj2.managerNextTime = this.autoform.employeNextTime;
            // obj2.managerNextTime = '';
            obj2.receiver = [];
            obj2.warningType = "1";
            param.push(obj2);
          }
          if (this.autoform.checked3) {
            let obj3 = {};
            obj3.managerOverdueDay = this.autoform.autoDay;
            // obj3.managerNextTime = "";
            let emyArr = [];
            emyArr.push(this.scrmPersonSopUserRels1[0].userId);
            obj3.receiver = emyArr;
            obj3.warningType = "2";
            param.push(obj3);
          }
          addWainingAuto(param).then((res) => {
            if (res.code == 200) {
              this.msgSuccess("保存成功");
              this.close();
            }
          });
        }
      });
    },
    //回显配置信息
    queryWarningAuto() {
      queryWarningAuto().then((res) => {
        this.deptList.splice(0, this.deptList.length);
        res.data.forEach((item) => {
          for (let i = 0; i < item.receiver.length; i++) {
            if (!this.isInArray2(this.deptList, item.receiver[i].deptId)) {
              this.deptList.push({
                deptId: item.receiver[i].deptId,
                children: [],
              });
            }
          }
          if (item.warningType == "0") {
            (this.autoform.checked1 = true),
              (this.autoform.managerOverdueDay = item.managerOverdueDay || "");
            // this.autoform.managerNextTime = item.managerNextTime || "";
            let receArr = [];
            console.log("分配员工", item.receiver);
            item.receiver.forEach((e) => {
              // let obj = [];
              // obj.push(e.deptId);
              // obj.push(e.userId);
              receArr.push({userId:e.userId , userName : e.userName})
              // receArr.push(obj);
              console.log(receArr);
            });
            // this.autoform.receiveManager = receArr || [];
            this.scrmPersonSopUserRels = receArr || [];
          } else if (item.warningType == "1") {
            (this.autoform.checked2 = true),
              (this.autoform.employeOverdueDay = item.managerOverdueDay || "");
            // this.autoform.employeNextTime = item.managerNextTime || "";
          } else if (item.warningType == "2") {
            console.log("兜底员工", item.receiver);
            (this.autoform.checked3 = true),
              (this.autoform.autoDay = item.managerOverdueDay || "");
            let emplArr = [];
            // emplArr.push(String(item.receiver[0].deptId));
            // emplArr.push(String(item.receiver[0].userId));
            emplArr.push({userId : item.receiver[0].userId , userName : item.receiver[0].userName})
            // this.autoform.employeBottom = emplArr || [];
            this.scrmPersonSopUserRels1 = emplArr || [];
          }
        });
        console.log(this.autoform);
        // this.getCustomers();
      });
    },

    isInArray(arr, value) {
      if (arr.indexOf && typeof arr.indexOf == "function") {
        var index = arr.indexOf(value);
        if (index != -1) {
          return true;
        }
      }
      return false;
    },

    isInArray2(arr, value) {
      for (let i = 0; i < arr.length; i++) {
        if (value == arr[i].deptId) {
          return arr[i].children;
        }
      }
      return false;
    },

    distributeEmployeListChange(val) {
      queryCustomers({ deptId: val[0] }).then((res) => {
        if (res.code === 200 && res.data.length) {
          res.data.forEach((item) => {
            item.value = item.userId;
            item.label = item.userName;
          });
          this.distributeEmployeList.forEach((item) => {
            if (item.value == val[0]) {
              item.children = res.data;
            }
          });
        }
      });
    },

    //提醒管理员
    //添加员工
    handleClick(){
      // let arr = [];
      // if(this.scrmPersonSopUserRels) this.scrmPersonSopUserRels.forEach(item => arr.push(item.userName))
      this.tableDataName = this.scrmPersonSopUserRels || [];
      this.selectUserVisible = true;
    },
    //删除员工
    handleClose(item) {
      this.scrmPersonSopUserRels = this.scrmPersonSopUserRels.filter((x) => {
        return x.userId != item.userId;
      });
    },
    //选中的员工数据
    selectUserConfirm(value) {
      // if(value && value.length > 1){
      //   this.$message.error('只支持选中一个员工');
      //   this.selectUserVisible = true;
      // }else{
        this.scrmPersonSopUserRels = [];
        value.forEach((item) => {
          this.scrmPersonSopUserRels.push({
            ...item,
          });
        });
      // }
    },

    //添加兜底员工
    //添加员工
    handleClick1(){
      // let arr = [];
      // if(this.scrmPersonSopUserRels1) this.scrmPersonSopUserRels1.forEach(item => arr.push(item.userName))
      this.tableDataName1 = this.scrmPersonSopUserRels1 || [];
      this.selectUserVisible1 = true;
    },
    //删除员工
    handleClose1(item) {
      this.scrmPersonSopUserRels1 = this.scrmPersonSopUserRels1.filter((x) => {
        return x.userId != item.userId;
      });
    },
    //选中的员工数据
    selectUserConfirm1(value) {
      if(value && value.length > 1){
        this.$message.error('只支持选中一个员工');
        this.selectUserVisible1 = true;
      }else{
      this.scrmPersonSopUserRels1 = [];
      value.forEach((item) => {
        this.scrmPersonSopUserRels1.push({
          ...item,
        });
      });
        console.log(this.scrmPersonSopUserRels1 , 'scrmPersonSopUserRels1' , '不会没值吧')
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";
.titleRow {
  margin: 12px 10px;
}
// .titleLine {
//   height: 16px;
//   border: #0f40f5 solid;
//   border-width: 2px;
//   border-radius: 20%;
//   margin-right: 10px;
// }

.textLine {
  line-height: 38px;
  margin: 8px;
}

.wrap {
  @include titleWrap;
  margin-bottom: 0px;
  padding-bottom: 0px;
  .title-header {
    border-bottom: 0px;
  }
}

::v-deep.vue-treeselect--has-value .vue-treeselect__multi-value {
  margin-bottom: 5px;
  line-height: 18px;
}
</style>

